/**
 * Utils
 * Created by yangbajing(yangbajing@gmail.com) on 2016-12-05.
 */
import lodashDifference from 'lodash/difference';
import lodashUniq from 'lodash/uniq';
import moment from 'moment';
import qs from 'qs';
import {browserHistory} from 'react-router';
import Constants from "../common/constants"

const Utils = {

    formatDatetime(text) {
        if (!text) {
            return '';
        }
        return moment(text).format('YYYY/MM/DD HH:mm:ss');
    },

    formatDate(text) {
        if (!text) {
            return '';
        }
        return moment(text).format('YYYY/MM/DD');
    },

    formatTime(text) {
        if (!text) {
            return '';
        }
        return moment(text).format('HH:mm:ss');
    },

    /**
     * 将对象属性里本应为数值类型的字段从字符类型转换成数值类型
     * @param params
     * @param paramNames
     * @return {{}}
     */
    transAttributesToNumber(params, paramNames) {
        if (!params) {
            return {};
        }

        let objs = {...params};
        // console.log('paramNames', paramNames);
        for (name of paramNames) {
            const value = objs[name];
            // console.log(`name: ${name}, value: ${value}`);
            if (value !== null && value !== undefined) {
                objs[name] = Number(value);
            }
        }
        return objs;
    },

    /**
     * 设置bowserHistory页面跳转
     * @param path 路径
     * @param params 查询参数
     */
    pushLink(path, params) {
        const querystring = qs.stringify(params);
        browserHistory.push(Constants.BASE_CONSOLE_URL + path + (querystring ? '?' + querystring : ''));
    },

    getToObject(imt, paramter) {
        return this.getToJS(imt, paramter, {});
    },

    getToArray(imt, paramter) {
        return this.getToJS(imt, paramter, []);
    },

    getToJS(imt, paramter, deft = {}) {
        const imtObj = imt.get(paramter);
        return imtObj ? imtObj.toJS() : deft;
    },

    getInToObject(imt, parameters) {
        return this.getInToJS(imt, parameters, {});
    },

    getInToArray(imt, parameters) {
        return this.getInToJS(imt, parameters, []);
    },

    getInToJS(imt, parameters, deft = {}) {
        const imtObj = imt.getIn(parameters);
        return imtObj ? imtObj.toJS() : deft;
    },

    arrayDiff(arr1, arr2) {
        const dl1 = lodashDifference(arr1, arr2);
        const dl2 = lodashDifference(arr2, arr1);
        return lodashUniq(dl1.concat(dl2));
    },

    isBlank(str) {
        if (!str || str == "") {
            return true;
        }
        const re = new RegExp('^[ ]+$');
        return re.test(str);
    },

    isNonBlank(str) {
        return !isBlank(str);
    },
};

export default Utils;

